package com.example.mytestdemo

import android.content.Context
import android.content.res.Resources
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.Log
import androidx.collection.LongSparseArray
import com.example.mytestdemo.databinding.ActivityEmptyMainBinding


/*
   组件化开发时  databinding使用报错的话，不仅当前 模块配置
    dataBinding {
        enabled = true
    }
    主项目模块也要配置
* java.lang.ClassNotFoundException: Didn't find class "androidx.databinding.Da
*
*
* */
class MainEmptyActivity : BaseViewBindActivity<ActivityEmptyMainBinding>() {


    override fun getLayoutInflateId(): Int {
        return R.layout.activity_empty_main
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        Log.d(TAG, "onCreate: ")
        super.onCreate(savedInstanceState)

        mBind.btRes.setOnClickListener{
            modifyDrawable()
            mBind.ivBg.setImageResource(R.drawable.bg_dlg_discount)
        }
    }

    override fun initData() {
        val handle = object : Handler(Looper.myLooper()!!) {
            override fun handleMessage(msg: Message) {
                super.handleMessage(msg)

            }
        }
    }
    

    override fun initUI() {
    }

    override fun setTheme(resId: Int) {
        val resId2 = R.style.ActivitySplash2
        super.setTheme(resId)
        Log.d(TAG, "setTheme: $resId ")
        Log.d(TAG, "setTheme: $resId2 ")

    }

    override fun getTheme(): Resources.Theme {
        // 创建一个新的主题对象
        val theme = super.getTheme()
        Log.d(TAG, "getTheme: ${theme}")

        theme.applyStyle(R.style.ActivitySplash2, true)
        Log.d(TAG, "getTheme2: ${theme}")

        return theme
    }

    fun replaceResource(context: Context) {
        // 将Bitmap对象转换为Drawable对象
        // 将Bitmap对象转换为Drawable对象
        val newDrawable: Drawable = context.resources.getDrawable(R.drawable.cat)

        try {
            // 获取Resources类的mDrawableCache和mDrawableCacheSize字段
            val drawableCacheField = Resources::class.java.getDeclaredField("mDrawableCache")
            drawableCacheField.isAccessible = true
            val drawableCache = drawableCacheField[resources]
            val drawableCacheSizeField =
                Resources::class.java.getDeclaredField("mDrawableCacheSize")
            drawableCacheSizeField.isAccessible = true
            val drawableCacheSize = drawableCacheSizeField.getInt(resources)

            // 遍历mDrawableCache字段，查找名为"ic_launcher"的Drawable对象
            val drawableMap: HashMap<String,Any> = drawableCache as HashMap<String,Any>
            drawableMap.forEach { entry->
                val value: Any = entry.value
                if (entry.key == "res/drawable/bg_dlg_discount.png") {
                    // 修改Drawable对象
                    val drawableField = value.javaClass.getDeclaredField("mDrawable")
                    drawableField.isAccessible = true
                    drawableField[value] = newDrawable
                    return
                }
            }


            // 清空mDrawableCache字段，以便下次重新加载资源
            drawableMap.clear()
            drawableCacheSizeField.setInt(resources, 0)
        } catch (e: Exception) {
            e.printStackTrace()
        }

    }

    private fun modifyDrawable() {
        try {
            // 获取 Resources 对象
            val resources = resources

            // 获取 Resources 类的 mResourcesImpl 字段
            val resourcesImplField = Resources::class.java.getDeclaredField("mResourcesImpl")
            resourcesImplField.isAccessible = true

            // 获取 ResourcesImpl 对象
            val resourcesImpl = resourcesImplField.get(resources)

            // 获取 ResourcesImpl 类的 mDrawableCache 字段
            val resourcesImplClass = Class.forName("android.content.res.ResourcesImpl")
            val drawableCacheField = resourcesImplClass.getDeclaredField("mDrawableCache")
            drawableCacheField.isAccessible = true
            val drawableCache = drawableCacheField.get(resourcesImpl)

            // 遍历 mDrawableCache 字段，查找名为 "ic_launcher_background" 的 Drawable 对象
            // 如果 drawableCache 是 LongSparseArray 类型，则按照 LongSparseArray 的方式进行遍历和修改
            if (drawableCache is LongSparseArray<*>) {
                for (i in 0 until drawableCache.size()) {
                    val drawableWrapper = drawableCache.valueAt(i)
                    if (drawableWrapper != null) {
                        val drawableClass = drawableWrapper::class.java
                        val mDrawableField = drawableClass.getDeclaredField("mDrawable")
                        mDrawableField.isAccessible = true
                        val drawable = mDrawableField.get(drawableWrapper)
                        mDrawableField.set(drawable, resources.getDrawable(R.drawable.cat))
                    }
                }
            } else if (drawableCache is Map<*, *>) { // 如果 drawableCache 是 HashMap 类型，则按照 HashMap 的方式进行遍历和修改
                // 遍历 drawableCache 字段，查找名为 "ic_launcher_background.png" 的 Drawable 对象
                for ((key, value) in drawableCache) {
                    if (key.toString().contains("ic_launcher_background.png")) {
                        // 修改 Drawable 对象
                        val drawableClass = value!!::class.java
                        val mDrawableField = drawableClass.getDeclaredField("mDrawable")
                        mDrawableField.isAccessible = true
                        mDrawableField.set(value, resources.getDrawable(R.drawable.cat))
                        break
                    }
                }
            }
            // 清空 mDrawableCache 字段，以便下次重新加载资源
            drawableCacheField.set(resourcesImpl, drawableCache)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }


    fun setImg(){
        val resources = Resources.getSystem()
        val resId = resources.getIdentifier("old_pic", "drawable", packageName)
}

}

